// src/components/anchored-heading.js

import { h } from 'vue'

const AnchoredHeading = {
    render() {
        const headingId = getChildrenTextContent(this.$slots.default())
        .toLowerCase()
        .replace(/\W+/g, '-')
        .replace(/(^-|-$)/g, '')

        //h()函数准确的说是createVNode()
        return h(   //返回的时虚拟DOM(VNode),准确的说是createNodeDescription
            'h' + this.level, // tag name
            [
                h(
                   'a',
                   {
                        name: headingId,
                        href: '#' + headingId
                   },
                   this.$slots.default()
                )
            ]
        )
    },
    props: {
        level: {
            type: Number,
            required: true
        }
    }
}

function getChildrenTextContent(children) {
    return children
    .map(node => {
        return typeof node.children === 'string'
          ? node.children
          : Array.isArray(node.children)
          ? getChildrenTextContent(node.children)
          : ''
    })
    .join('')
}

export default AnchoredHeading